/**
 * https://github.com/jinke18/educoder_weapp
 * @licence GPL-3.0
 * @author jinke18
 */

import apiConfig from "./apiConfig";
import ds from "./ds";
import { getResConstruction } from "./utils";

export default class Client {
  constructor({ session } = {}) {
    this.cb = {
      before: {},
      success: {},
      fail: {}
    };
    this.initCallback();
  }
  on(cd, name, cb) {
    this.cb[cd][name] = cb;
  }
  trigger(cd, name, data) {
    if (typeof this.cb[cd][name] == "function")
      return this.cb[cd][name](data);
    else
      return this.cb[cd][name];
  }
  initCallback() {

  }
  showApiList(){
    let list = Object.keys(apiConfig).map(api=>({[api]:apiConfig[api].disp||""}))
    console.log("api列表：\n", ...list);
    return list;
  }
  api(name, config = {}) {
    return ({success, fail, complete, ...data}={}) => {
      return this.callApi({ name, config, data, success, fail, success });
    }
  }
  callApi({ name, data = {}, config = {}, success, fail, complete }) {
    //console.debug("client.callApi", arguments[0]);
    return ds({
      name, config, data: { ...this.trigger("before", name, data), ...data},
      success: res => {
        this.trigger("success", name, res);
        console.debug(`督诗api ${name}成功返回的数据有\n${JSON.stringify(res, null, 2)}`);
        console.info(`督诗api ${name}成功返回的数据结构是:`, getResConstruction(res));
        if (success)
          success(res)
      }, fail: e => {
        this.trigger("fail", name, e);
        if (fail)
          fail(e);
      }, complete,
    });
  }
}

export const client = global.client = new Client();